<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript基础语法示例</title>
  <style>
    body {
      font-family: 'Arial', sans-serif;
      line-height: 1.6;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      color: #333;
    }
    h1 {
      color: #2c3e50;
      border-bottom: 2px solid #eee;
      padding-bottom: 10px;
    }
    .example {
      background-color: #f8f9fa;
      border-left: 4px solid #42b983;
      padding: 15px;
      margin-bottom: 20px;
      border-radius: 0 4px 4px 0;
    }
    .output {
      background-color: #f1f1f1;
      padding: 10px;
      border-radius: 4px;
      margin-top: 10px;
      font-family: monospace;
    }
    button {
      background-color: #42b983;
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
      margin-right: 5px;
      margin-bottom: 5px;
    }
    button:hover {
      background-color: #3aa876;
    }
    code {
      background-color: #f1f1f1;
      padding: 2px 5px;
      border-radius: 3px;
      font-family: monospace;
    }
  </style>
</head>
<body>
  <h1>JavaScript基础语法示例</h1>
  
  <div class="example">
    <h2>变量和数据类型</h2>
    <button onclick="showVariables()">运行示例</button>
    <div id="variables-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>运算符</h2>
    <button onclick="showOperators()">运行示例</button>
    <div id="operators-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>条件语句</h2>
    <input type="number" id="age-input" placeholder="输入年龄" value="18">
    <button onclick="checkAge()">检查年龄</button>
    <div id="conditions-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>循环语句</h2>
    <button onclick="runLoops()">运行循环</button>
    <div id="loops-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>函数</h2>
    <input type="text" id="name-input" placeholder="输入姓名" value="张三">
    <button onclick="greetUser()">问候</button>
    <button onclick="calculateSum()">计算1到10的和</button>
    <div id="functions-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>数组操作</h2>
    <button onclick="demonstrateArrays()">数组示例</button>
    <div id="arrays-output" class="output"></div>
  </div>
  
  <div class="example">
    <h2>对象操作</h2>
    <button onclick="demonstrateObjects()">对象示例</button>
    <div id="objects-output" class="output"></div>
  </div>

  <script>
    // 辅助函数：将内容添加到输出区域
    function appendToOutput(outputId, content) {
      const output = document.getElementById(outputId);
      output.innerHTML += content + '<br>';
    }
    
    // 辅助函数：清空输出区域
    function clearOutput(outputId) {
      const output = document.getElementById(outputId);
      output.innerHTML = '';
    }
    
    // 变量和数据类型示例
    function showVariables() {
      clearOutput('variables-output');
      
      // 变量声明
      let message = "Hello";
      var name = "John";
      const PI = 3.14159;
      
      // 基本数据类型
      let string = "这是一个字符串";
      let number = 42;
      let boolean = true;
      let nullValue = null;
      let undefinedValue;
      
      // 复杂数据类型
      let array = [1, 2, 3, 4];
      let object = {
        name: "Alice",
        age: 25,
        isStudent: true
      };
      
      // 输出变量和类型
      appendToOutput('variables-output', `字符串: ${string} (${typeof string})`);
      appendToOutput('variables-output', `数字: ${number} (${typeof number})`);
      appendToOutput('variables-output', `布尔值: ${boolean} (${typeof boolean})`);
      appendToOutput('variables-output', `Null: ${nullValue} (${typeof nullValue})`);
      appendToOutput('variables-output', `Undefined: ${undefinedValue} (${typeof undefinedValue})`);
      appendToOutput('variables-output', `数组: [${array}] (${typeof array})`);
      appendToOutput('variables-output', `对象: ${JSON.stringify(object)} (${typeof object})`);
    }
    
    // 运算符示例
    function showOperators() {
      clearOutput('operators-output');
      
      // 算术运算符
      let sum = 5 + 3;
      let difference = 10 - 4;
      let product = 7 * 2;
      let quotient = 20 / 5;
      let remainder = 10 % 3;
      let power = 2 ** 3;
      
      appendToOutput('operators-output', `5 + 3 = ${sum}`);
      appendToOutput('operators-output', `10 - 4 = ${difference}`);
      appendToOutput('operators-output', `7 * 2 = ${product}`);
      appendToOutput('operators-output', `20 / 5 = ${quotient}`);
      appendToOutput('operators-output', `10 % 3 = ${remainder}`);
      appendToOutput('operators-output', `2 ** 3 = ${power}`);
      
      // 比较运算符
      appendToOutput('operators-output', `5 == "5": ${5 == "5"}`);
      appendToOutput('operators-output', `5 === "5": ${5 === "5"}`);
      appendToOutput('operators-output', `10 > 5: ${10 > 5}`);
      appendToOutput('operators-output', `10 < 5: ${10 < 5}`);
      
      // 逻辑运算符
      appendToOutput('operators-output', `true && false: ${true && false}`);
      appendToOutput('operators-output', `true || false: ${true || false}`);
      appendToOutput('operators-output', `!true: ${!true}`);
    }
    
    // 条件语句示例
    function checkAge() {
      clearOutput('conditions-output');
      
      const age = parseInt(document.getElementById('age-input').value);
      
      // if语句
      if (age >= 18) {
        appendToOutput('conditions-output', `if语句: ${age}岁，成年人`);
      } else {
        appendToOutput('conditions-output', `if语句: ${age}岁，未成年人`);
      }
      
      // if-else if-else语句
      if (age < 12) {
        appendToOutput('conditions-output', `if-else if: ${age}岁，儿童`);
      } else if (age < 18) {
        appendToOutput('conditions-output', `if-else if: ${age}岁，青少年`);
      } else if (age < 60) {
        appendToOutput('conditions-output', `if-else if: ${age}岁，成年人`);
      } else {
        appendToOutput('conditions-output', `if-else if: ${age}岁，老年人`);
      }
      
      // 三元运算符
      const result = (age >= 18) ? "成年人" : "未成年人";
      appendToOutput('conditions-output', `三元运算符: ${age}岁，${result}`);
      
      // switch语句
      let ageGroup;
      switch (true) {
        case (age < 12):
          ageGroup = "儿童";
          break;
        case (age < 18):
          ageGroup = "青少年";
          break;
        case (age < 60):
          ageGroup = "成年人";
          break;
        default:
          ageGroup = "老年人";
      }
      appendToOutput('conditions-output', `switch语句: ${age}岁，${ageGroup}`);
    }
    
    // 循环语句示例
    function runLoops() {
      clearOutput('loops-output');
      
      // for循环
      let forOutput = "for循环: ";
      for (let i = 1; i <= 5; i++) {
        forOutput += i + " ";
      }
      appendToOutput('loops-output', forOutput);
      
      // while循环
      let whileOutput = "while循环: ";
      let count = 1;
      while (count <= 5) {
        whileOutput += count + " ";
        count++;
      }
      appendToOutput('loops-output', whileOutput);
      
      // do-while循环
      let doWhileOutput = "do-while循环: ";
      let num = 1;
      do {
        doWhileOutput += num + " ";
        num++;
      } while (num <= 5);
      appendToOutput('loops-output', doWhileOutput);
      
      // for...of循环
      let colors = ["红", "绿", "蓝"];
      let forOfOutput = "for...of循环: ";
      for (let color of colors) {
        forOfOutput += color + " ";
      }
      appendToOutput('loops-output', forOfOutput);
      
      // for...in循环
      let person = { name: "张三", age: 30, job: "工程师" };
      let forInOutput = "for...in循环: ";
      for (let key in person) {
        forInOutput += `${key}:${person[key]} `;
      }
      appendToOutput('loops-output', forInOutput);
    }
    
    // 函数示例
    function greetUser() {
      clearOutput('functions-output');
      const name = document.getElementById('name-input').value;
      
      // 函数声明
      function greet(name) {
        return `你好，${name}！`;
      }
      appendToOutput('functions-output', greet(name));
      
      // 函数表达式
      const greetFormal = function(name) {
        return `尊敬的${name}，您好！`;
      };
      appendToOutput('functions-output', greetFormal(name));
      
      // 箭头函数
      const greetCasual = (name) => `嘿，${name}！`;
      appendToOutput('functions-output', greetCasual(name));
    }
    
    function calculateSum() {
      clearOutput('functions-output');
      
      // 使用循环计算和
      function sumLoop(n) {
        let sum = 0;
        for (let i = 1; i <= n; i++) {
          sum += i;
        }
        return sum;
      }
      
      // 使用递归计算和
      function sumRecursive(n) {
        if (n <= 1) return n;
        return n + sumRecursive(n - 1);
      }
      
      // 使用数学公式计算和
      function sumFormula(n) {
        return n * (n + 1) / 2;
      }
      
      const n = 10;
      appendToOutput('functions-output', `1到${n}的和（循环）: ${sumLoop(n)}`);
      appendToOutput('functions-output', `1到${n}的和（递归）: ${sumRecursive(n)}`);
      appendToOutput('functions-output', `1到${n}的和（公式）: ${sumFormula(n)}`);
    }
    
    // 数组操作示例
    function demonstrateArrays() {
      clearOutput('arrays-output');
      
      // 创建数组
      let fruits = ["苹果", "香蕉", "橙子"];
      appendToOutput('arrays-output', `原始数组: ${fruits}`);
      
      // 添加和删除元素
      fruits.push("葡萄");
      appendToOutput('arrays-output', `push后: ${fruits}`);
      
      fruits.pop();
      appendToOutput('arrays-output', `pop后: ${fruits}`);
      
      fruits.unshift("草莓");
      appendToOutput('arrays-output', `unshift后: ${fruits}`);
      
      fruits.shift();
      appendToOutput('arrays-output', `shift后: ${fruits}`);
      
      // 数组方法
      appendToOutput('arrays-output', `索引2的元素: ${fruits[2]}`);
      appendToOutput('arrays-output', `数组长度: ${fruits.length}`);
      appendToOutput('arrays-output', `"香蕉"的索引: ${fruits.indexOf("香蕉")}`);
      
      // 数组转换
      appendToOutput('arrays-output', `join: ${fruits.join(" - ")}`);
      
      // 数组迭代
      let mapResult = fruits.map(fruit => fruit.toUpperCase());
      appendToOutput('arrays-output', `map: ${mapResult}`);
      
      let filterResult = fruits.filter(fruit => fruit.length > 2);
      appendToOutput('arrays-output', `filter: ${filterResult}`);
    }
    
    // 对象操作示例
    function demonstrateObjects() {
      clearOutput('objects-output');
      
      // 创建对象
      let person = {
        name: "张三",
        age: 30,
        job: "工程师",
        skills: ["JavaScript", "HTML", "CSS"],
        address: {
          city: "北京",
          district: "海淀区"
        },
        greet: function() {
          return `你好，我是${this.name}，今年${this.age}岁。`;
        }
      };
      
      // 访问对象属性
      appendToOutput('objects-output', `姓名: ${person.name}`);
      appendToOutput('objects-output', `年龄: ${person["age"]}`);
      appendToOutput('objects-output', `城市: ${person.address.city}`);
      appendToOutput('objects-output', `第一个技能: ${person.skills[0]}`);
      appendToOutput('objects-output', `问候: ${person.greet()}`);
      
      // 修改对象
      person.age = 31;
      person.skills.push("React");
      appendToOutput('objects-output', `修改后的年龄: ${person.age}`);
      appendToOutput('objects-output', `修改后的技能: ${person.skills}`);
      
      // 添加新属性
      person.email = "zhangsan@example.com";
      appendToOutput('objects-output', `新添加的邮箱: ${person.email}`);
      
      // 获取所有键
      appendToOutput('objects-output', `所有键: ${Object.keys(person)}`);
    }
  </script>
</body>
</html>